package com.openlogic.common.core.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.openlogic.common.core.constants.HttpConstant;
import com.openlogic.common.core.exception.ServiceException;

/**
 * @ClassName: AuthDataScopeUtils
 * @Description: 数据权限全局线程变量
 * @author weiyongpeng
 * @date 2025年1月30日 下午8:36:49
 */
public class AuthDataScopeUtils {

	public static ThreadLocal<JSONObject> localHeader = new ThreadLocal<>();

	/**
	 * 获取数据权限
	 * 
	 * @return
	 */
	public static boolean isTenant() {
		return Boolean.TRUE.equals(getValue("isTenant", Boolean.class, false));
	}

	/**
	 * 获取数据权限
	 * 
	 * @return
	 */
	public static boolean isTenant(boolean autoException) {
		return Boolean.TRUE.equals(getValue("isTenant", Boolean.class, autoException));
	}

	/**
	 * 是否进行租户查询
	 * 
	 * @param isTenant
	 */
	public static void setIsTenant(boolean isTenant) {
		setValue("isTenant", isTenant);
	}

	/**
	 * 设置值
	 * 
	 * @param name  名称
	 * @param value 设置值
	 */
	private static void setValue(String name, Object value) {
		if (localHeader.get() == null) {
			localHeader.set(new JSONObject());
		}
		localHeader.get().put(name, value);
	}

	private static <T> T getValue(String name, Class<T> clazz, boolean autoException) {
		if (localHeader.get() != null && localHeader.get().containsKey(name)) {
			return JSON.to(clazz, localHeader.get().get(name));
		} else {
			if (autoException) {
				throw new ServiceException("数据权限异常", HttpConstant.DATA_SCOPE_ERROR);
			}
			return null;
		}
	}

	/**
	 * 清除线程数据
	 */
	public static void clear() {
		localHeader.remove();
	}

}